<template>
  <a-modal :visible="visible" :title="'历史版本'" :footer="null" :width="350" @cancel="handleCancel">
    <a-table :columns="columns" :data-source="tableDataTime" bordered size="small" :pagination="false">
      <template #operation="{ record }">
        <a-button type="link" @click="handleRecoverHistory(record)"> 恢复到此版本 </a-button>
      </template>
    </a-table>
  </a-modal>
</template>

<script setup>
  import { ref, reactive, computed, defineExpose } from 'vue';
  import { historyFlow } from '../design.api';
  import moment from 'moment-timezone';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { Modal } from 'ant-design-vue';
  const { createMessage: $message } = useMessage();
  const props = defineProps({
    id: { type: String },
    editor: { type: Object },
  });
  const visible = ref(false);
  const columns = reactive([
    {
      title: '修改时间',
      dataIndex: 'date',
    },
    {
      title: '操作',
      dataIndex: 'timestamp',
      width: 120,
      slots: {
        customRender: 'operation',
      },
    },
  ]);

  
  const tableData = ref([]);
  const tableDataTime = computed(() => {
    return tableData.value.map((item, index) => {
      return {
        key: index,
        timestamp: item,
        date: moment(item).format('YYYY-MM-DD HH:mm:ss'),
      };
    });
  });

  function historyAction() {
    historyFlow({ id: props.id }).then((res) => {
      tableData.value = res;
      if (tableData.value || tableData.value.length > 0) {
        visible.value = true;
      } else {
        $message.info('暂无历史版本！');
      }
    });
  }

  function handleRecoverHistory(record) {
    Modal.confirm({
      title: '信息',
      content: '确定要恢复到该版本吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        historyFlow({ id: props.id, timestamp: record.timestamp }).then((res) => {
          props.editor?.getGraph().inputXml(res);
          visible.value = false;
        });
      },
    });
  }

  function handleCancel() {
    visible.value = false;
  }

  defineExpose({
    historyAction,
  });
</script>
